import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart' ;
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:mfkb/config/Config.dart';
import 'package:mfkb/pages/modules/CustomRoute.dart';
import 'package:mfkb/pages/modules/Nothing.dart';
import 'package:mfkb/pages/school/Publish.dart';
import 'package:mfkb/pages/school/RelationDetail.dart';
import 'package:mfkb/pages/school/plugins/ImageSwiper.dart';
import 'package:mfkb/service/DynamicService.dart';
import 'package:photo_view/photo_view.dart';
import 'package:toast/toast.dart';

class SchoolRelation extends StatefulWidget {
  @override
  _SchoolRelationState createState() => _SchoolRelationState();
}

class _SchoolRelationState extends State<SchoolRelation> {

  List<dynamic> _list = null ;
  ScrollController _controller = new ScrollController();
  var flag = true ; // 是否还有数据
  var swiper_list = null ;
  var swiper_show = false ;
  var swiper_index = 0 ;
  int lastId = 99999999 ;
  var loading = false ;
  bool isLoading = false ;

  @override
  void initState() {
    super.initState();
    getData();
    //给_controller添加监听
    _controller.addListener((){
      //判断是否滑动到了页面的最底部
      if(_controller.position.pixels >= _controller.position.maxScrollExtent){
        //如果不是最后一页数据，则生成新的数据添加到list里面
        if(flag && !isLoading){
          _retrieveData();
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.dark ,
      child: Scaffold(
        body: Stack(
          children: <Widget>[
            Column(
              children: <Widget>[
                Container(
                  height: MediaQuery.of(context).padding.top ,
                  color: Colors.white ,
                ) ,
                Container(
                  height: 45,
                  decoration: BoxDecoration(
                    color:Colors.white ,
                    border: Border(
                      bottom: BorderSide(
                        color:Color.fromARGB(255, 246, 246, 246) ,
                        width: ScreenUtil().setHeight(1)
                      )
                    )
                  ),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start ,              
                    children: <Widget>[
                      Container(
                        width: ScreenUtil().setWidth(30),
                        height: ScreenUtil().setWidth(17),
                        margin: EdgeInsets.only(left:ScreenUtil().setWidth(15)),
                        child: GestureDetector(
                          child: Container(
                            width: ScreenUtil().setWidth(17),
                            margin: EdgeInsets.only(right:ScreenUtil().setWidth(13)),
                            child: Image.asset("assets/images/back.png" , fit: BoxFit.fill,),
                          ),
                          onTap: (){
                            Navigator.of(context).pop() ;
                          },
                        ),
                      ) ,
                      Expanded(
                        child: Center(
                          child: Text("校园交友" , style: TextStyle(
                            fontSize: ScreenUtil().setSp(18) ,
                            decoration: TextDecoration.none ,
                            color: Color.fromARGB(255, 19, 28, 53)
                          )),
                        ),
                      ) ,
                      Container(
                        width: ScreenUtil().setWidth(30),
                        height: ScreenUtil().setWidth(17),
                        margin: EdgeInsets.only(right:ScreenUtil().setWidth(15)),
                        child: GestureDetector(
                          child: Container(
                            child: Text("发布" , style: TextStyle(
                              fontSize: ScreenUtil().setSp(14) ,
                              color: Color.fromARGB(255, 0, 167, 187) ,
                              height: ScreenUtil().setHeight(17) / ScreenUtil().setSp(14) ,
                              decoration: TextDecoration.none
                            ),),
                          ),
                          onTap: () async{
                            var result = await Navigator.of(context).push(CustomRoute(Publish())) ;
                            if(result != null){
                              getData() ;
                            }
                          },
                        )
                      )
                    ],
                  ),
                ) ,
                Expanded(
                  child: Container(
                    color: Colors.white,
                    width: ScreenUtil().setWidth(375),
                    child: _list == null || _list.length == 0 ? Container(
                      color: Colors.white ,
                      width: ScreenUtil().setWidth(375),
                      child: Nothing(),
                    ) : RefreshIndicator(
                      onRefresh: _onRefresh,
                      child: new ListView.separated(
                        padding: EdgeInsets.all(0),
                        controller: _controller,
                        physics: BouncingScrollPhysics(),
                        itemBuilder: (context,index){
                          return GestureDetector(
                            child: Container(
                              margin: EdgeInsets.only(left:ScreenUtil().setWidth(15) , right:ScreenUtil().setWidth(14)),
                              color: Colors.white ,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start ,
                                children: <Widget>[
                                  Container(
                                    height: ScreenUtil().setWidth(40),
                                    margin: EdgeInsets.only(top:ScreenUtil().setHeight(14)),
                                    child: Row(
                                      children: <Widget>[
                                        Container(
                                          width: ScreenUtil().setWidth(40) ,
                                          height: ScreenUtil().setWidth(40) ,
                                          child: ClipRRect(
                                            borderRadius: BorderRadius.all(Radius.circular(ScreenUtil().setWidth(40))),
                                            child: CachedNetworkImage(
                                              imageUrl: Config().getImgHost() + _list[index]["icon"] ,
                                              placeholder: (contex , url){
                                                return Container(
                                                  color:Color.fromARGB(255, 246, 245, 248) ,
                                                  child: Center(
                                                    child: Image.asset("assets/images/imageloading.png"),
                                                  ) ,
                                                ) ;
                                              },
                                            ),
                                          )
                                        ) ,
                                        Expanded(
                                          child: Container(
                                            child: Column(
                                              crossAxisAlignment: CrossAxisAlignment.start,
                                              children: <Widget>[
                                                Container(
                                                  height: ScreenUtil().setWidth(25),
                                                  child: Row(
                                                    children: <Widget>[
                                                      Expanded(
                                                        child: Container(
                                                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(10)),
                                                          child: Text(_list[index]["nickname"] , style: TextStyle(
                                                            fontSize: ScreenUtil().setSp(16) ,
                                                            color: Color.fromARGB(255, 19, 28, 53) ,
                                                            fontWeight: FontWeight.bold ,
                                                            fontFamily: "PingFang-SC-Bold,PingFang-SC"
                                                          ),),
                                                        ),
                                                      ) ,
                                                      Container(
                                                        width: ScreenUtil().setWidth(80),
                                                        child: Text(
                                                          _list[index]["time"] , style: TextStyle(
                                                            fontSize: ScreenUtil().setSp(10) ,
                                                            color: Color.fromARGB(255, 121, 132, 155)
                                                          ),textAlign: TextAlign.end ,
                                                        ),
                                                      )
                                                    ],
                                                  ),
                                                ) ,
                                                Container(
                                                  height: ScreenUtil().setWidth(15),
                                                  margin: EdgeInsets.only(left:ScreenUtil().setWidth(10)),
                                                  child: Text(_list[index]["school"] , textAlign: TextAlign.start,style: TextStyle(
                                                    fontSize: ScreenUtil().setSp(12) ,
                                                    height: ScreenUtil().setWidth(13) / ScreenUtil().setSp(12),
                                                    color:Color.fromARGB(255, 121, 132, 155)
                                                  ),),
                                                )
                                              ],
                                            ),
                                          ),
                                        ) ,
                                      ],
                                    ),
                                  ) ,
                                  Container(
                                    margin: EdgeInsets.only(top:ScreenUtil().setHeight(14)),
                                    child: Text(_list[index]["content"] , style: TextStyle(
                                      fontSize: ScreenUtil().setSp(14) ,
                                      fontWeight: FontWeight.w500 
                                    ),),
                                  ) ,
                                  Visibility(
                                    visible: _list[index]["images"] != null && _list[index]["images"].length != 0,
                                    child: Container(
                                      margin: EdgeInsets.only(top:ScreenUtil().setHeight(_list[index]["images"] == null || _list[index]["images"].length == 0 ? 0 : 14)),
                                      child: Row(
                                        children: List.generate(_list[index]["images"] == null ? 0 : _list[index]["images"].length, (i){
                                          return  Container(
                                            width: ScreenUtil().setWidth(110),
                                            height: ScreenUtil().setWidth(110),
                                            decoration: BoxDecoration(
                                              color: Colors.black ,
                                              borderRadius: BorderRadius.all(Radius.circular(8)),
                                            ),
                                            margin: EdgeInsets.only(left:ScreenUtil().setWidth(i == 0 ? 0 : 8)),
                                            child: GestureDetector(
                                              child: ClipRRect(
                                                borderRadius: BorderRadius.all(Radius.circular(8)),
                                                child:CachedNetworkImage(
                                                  key: _list[index]["images"][i]["id"] ,
                                                  imageUrl: Config().getHost()+_list[index]["images"][i]["url"],
                                                  fit: BoxFit.cover ,
                                                  placeholder: (contex , url){
                                                    return Container(
                                                      color:Color.fromARGB(255, 246, 245, 248) ,
                                                      child: Center(
                                                        child: Image.asset("assets/images/imageloading.png"),
                                                      ) ,
                                                    ) ;
                                                  },
                                                )
                                              ) ,
                                              onTap: (){  
                                                setState(() { 
                                                  swiper_list = _list[index]["images"] ;
                                                  //swiper_show = true ;
                                                  swiper_index = i ;
                                                  Navigator.of(context).push(CustomRoute(ImageShowServerWidget(
                                                    initialIndex: swiper_index,
                                                    photoList: swiper_list,
                                                  ))) ;

                                                });
                                              },
                                            )
                                          ) ;
                                        }),
                                      ),
                                    ),
                                  ) ,
                                  Container(
                                    height: ScreenUtil().setWidth(20),
                                    margin: EdgeInsets.only(bottom:ScreenUtil().setHeight(22) , top:ScreenUtil().setHeight(22)),
                                    child: Row(
                                      children: <Widget>[
                                        Container(
                                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(144)),
                                          width: ScreenUtil().setWidth(80),
                                          child:GestureDetector(
                                            child: Row(
                                              children: <Widget>[
                                                Container(
                                                  width: ScreenUtil().setWidth(20),
                                                  height: ScreenUtil().setWidth(20),
                                                  child: Image.asset("assets/images/talk.png"),
                                                ) ,
                                                Expanded(
                                                  child: Container(
                                                    margin: EdgeInsets.only(left:ScreenUtil().setWidth(5)),
                                                    child: Text(_list[index]["talk"].toString() , style: TextStyle(
                                                      fontSize: ScreenUtil().setSp(14) ,
                                                      color: Color.fromARGB(255, 121, 132, 155)
                                                    ),),
                                                  )
                                                )
                                              ],
                                            ),
                                            onTap: (){
                                              Navigator.of(context).push(CustomRoute(RelationDetail(id: _list[index]["id"],))) ;
                                            },
                                          )
                                        ) ,
                                        Container(
                                          margin: EdgeInsets.only(left:ScreenUtil().setWidth(50)),
                                          width: ScreenUtil().setWidth(70),
                                          child:GestureDetector(
                                            child: Row(
                                              children: <Widget>[
                                                Container(
                                                  width: ScreenUtil().setWidth(20),
                                                  height: ScreenUtil().setWidth(20),
                                                  child: _list[index]["gid"] == null ? Image.asset("assets/images/up.png") : Image.asset("assets/images/up_active.png"),
                                                ) ,
                                                Expanded(
                                                  child: Container(
                                                    margin: EdgeInsets.only(left:ScreenUtil().setWidth(5)),
                                                    child: Text(_list[index]["up"].toString() , style: TextStyle(
                                                      fontSize: ScreenUtil().setSp(14) ,
                                                      color: Color.fromARGB(255, 121, 132, 155)
                                                    ),),
                                                  )
                                                )
                                              ],
                                            ),
                                            onTap: () {
                                              if(_list[index]["gid"] == null){
                                                DynamicService().up(_list[index]["id"] , 1).then((value){
                                                  if(value["code"] == 200){
                                                    setState(() {
                                                      _list[index]["gid"] = 1 ;
                                                      _list[index]["up"]++ ;
                                                    });
                                                  }  
                                                }) ;
                                              }else{
                                                DynamicService().up(_list[index]["id"] , 0).then((value){
                                                  if(value["code"] == 200){
                                                    setState(() {
                                                      _list[index]["gid"] = null ;
                                                      _list[index]["up"]-- ;
                                                    });
                                                  }  
                                                }) ;
                                              }
                                            },
                                          )
                                        )
                                      ],
                                    ),
                                  ) ,
                                  Container(
                                    height: ScreenUtil().setHeight(1),
                                    color: Color.fromARGB(255, 236, 237, 241),
                                  )
                                ],
                              ),
                            ) ,
                            onTap: (){
                              Navigator.of(context).push(CustomRoute(RelationDetail(id:_list[index]["id"]))) ;
                            },
                          );
                        },
                        //分割线构造器
                        separatorBuilder: (context,index){
                          return Container(
                            height: ScreenUtil().setHeight(8),
                          );
                        },
                        //_items.length + 1是为了给最后一行的加载loading留出位置
                        itemCount: _list.length 
                      ),
                    )
                  ),
                )
              ],
            ) ,
            // Visibility(
            //   visible: swiper_show ,
            //   child: WillPopScope(
            //     child: Container(
            //       color: Colors.black ,
            //       // child: Swiper(
            //       //   loop: false ,
            //       //   autoplay: false ,
            //       //   index: swiper_index ,
            //       //   itemCount: swiper_list == null ? 0 : swiper_list.length ,
            //       //   itemBuilder: (context , index){
            //       //     return GestureDetector(
            //       //       child: Container(
            //       //         width: ScreenUtil().setWidth(375),
            //       //         // child: CachedNetworkImage(
            //       //         //   imageUrl: Config().getHost()+swiper_list[index]["url"],
            //       //         //   fit: BoxFit.fitWidth ,
            //       //         //   placeholder: (contex , url){
            //       //         //     return Container(
            //       //         //       color:Color.fromARGB(255, 246, 245, 248) ,
            //       //         //       child: Center(
            //       //         //         child: Image.asset("assets/images/imageloading.png"),
            //       //         //       ) ,
            //       //         //     ) ;
            //       //         //   },
            //       //         // ),
            //       //         child: PhotoView(
            //       //           imageProvider: CachedNetworkImageProvider(Config().getHost()+swiper_list[index]["url"]),
            //       //         ),
            //       //       ),
            //       //       onTap: (){
            //       //         setState(() {
            //       //           swiper_show = false ;
            //       //         });
            //       //       },
            //       //     ) ;
            //       //   },
            //       // ),
            //       child: ImageShowServerWidget(
            //         initialIndex: 0 ,
            //         photoList: swiper_list,
            //       ),
            //     ),
            //     onWillPop: (){
            //       setState(() {
            //         swiper_show = false ;
            //       });
            //     },
            //   ),
            // ) ,
            Visibility(
              visible: loading,
              child: Container(
                color: Color.fromARGB(160, 0, 0, 0),
                width: ScreenUtil().setWidth(375),
                height: ScreenUtil().setHeight(812),
                child: Container(
                  width: ScreenUtil().setWidth(150),
                  height: ScreenUtil().setWidth(150),
                  child: Center(
                    child: Text("正在加载..." , style: TextStyle(color: Colors.white),),
                  ),
                ),
              ),
            )
          ],
        ),
      )
    ) ;
  }

  void getData() {
    lastId = 9999999 ;
    flag = true ;
    //初始数据源
    DynamicService().getDynamics(0).then((data){
      if(data["code"] == 200){
        if(data["data"].length < 10){
          flag = false ;
        }
        _list = data["data"] ;
        for(var i = 0 ; i < _list.length ; i++){
          if(_list[i]["id"] < lastId){
            lastId = _list[i]["id"] ;
          }
        }
        setState(() {});
      }else{
        Toast.show(data["msg"], context) ;
      }
    }) ;
  }

  void _retrieveData() async {
    isLoading = true ;
    if(lastId == 0){
      Toast.show("已经到底了", context) ;
    }else{
      Future.delayed(Duration(milliseconds: 0) , (){
        DynamicService().getDynamics(lastId).then((data){
          if(data != null && data["code"] == 200){
            if(data["data"].length < 10){
              flag = false ;
            }
            for(var i = 0 ; i < data["data"].length ; i++){
              _list.add(data["data"][i]) ;
            }
            for(var i = 0 ; i < _list.length ; i++){
              if(_list[i]["id"] < lastId){
                lastId = _list[i]["id"] ;
              }
            }
            _controller.jumpTo(_controller.offset+ScreenUtil().setHeight(40)) ;
            setState(() {});   
            isLoading = false ;      
          }else{
            Toast.show(data["msg"], context) ;
            isLoading = false ;
          }
        }) ;
      }) ;
    }
  }

  // 下拉刷新
  Future<void> _onRefresh() async {
    await Future.delayed(Duration(milliseconds: 200) , (){
      getData() ;
    }) ;
  }

  @override
  void dispose() {
    //移除监听，防止内存泄漏
    _controller.dispose();
    super.dispose();
  }
}